import 'package:chatgreat/bloc/gallery_bloc.dart';
import 'package:chatgreat/helper/constant.dart';
import 'package:chatgreat/helper/haptic_feedback.dart';
import 'package:chatgreat/helper/helper.dart';
import 'package:chatgreat/helper/image.dart';
import 'package:chatgreat/helper/my_widget.dart';
import 'package:chatgreat/lang/lang.dart';
import 'package:chatgreat/page/component/attached_button_panel.dart';
import 'package:chatgreat/page/component/background_container.dart';
import 'package:chatgreat/page/component/button.dart';
import 'package:chatgreat/page/component/image_preview.dart';
import 'package:chatgreat/page/component/dialog.dart';
import 'package:chatgreat/page/component/theme/custom_size.dart';
import 'package:chatgreat/page/component/theme/custom_theme.dart';
import 'package:chatgreat/repo/api/creative.dart';
import 'package:chatgreat/repo/api_server.dart';
import 'package:chatgreat/repo/settings_repo.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:clipboard/clipboard.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'package:widgets_to_image/widgets_to_image.dart';

import '../../../helper/AppUtil.dart';
import '../../../helper/event.dart';
import 'data/gallery_home_data.dart';

class GalleryItemScreen extends StatefulWidget {
  final SettingRepository setting;
  final CreativeGallery creativeGallery;
  final int galleryId;

  const GalleryItemScreen({
    super.key,
    required this.setting,
    required this.creativeGallery,
    required this.galleryId,
  });

  @override
  State<GalleryItemScreen> createState() => _GalleryItemScreenState();
}

class _GalleryItemScreenState extends State<GalleryItemScreen> {
  final GalleryHomeData _homeData = GalleryHomeData();
  final WidgetsToImageController controller = WidgetsToImageController();
  
  @override
  void initState() {
    _homeData.loadData();
    super.initState();

    context
        .read<GalleryBloc>()
        .add(GalleryItemLoadEvent(creativeGallery: widget.creativeGallery));
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final customColors = Theme.of(context).extension<CustomColors>()!;

    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('images/bg1.png'),
          fit: BoxFit.fill,
        ),
      ),
      child: Scaffold(
        appBar: AppBar(
          elevation: 0,
          title: Text(
            isNotBlank(widget.creativeGallery.title ?? '')
                ? widget.creativeGallery.title!
                : '',
            style: const TextStyle(
              fontSize: 18,
            ),
          ),
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back,
              color: customColors.weakLinkColor,
            ),
            onPressed: () {
              GlobalEvent().emit('refresh_gallery');
              context.pop();
            },
          ),
          backgroundColor: Colors.transparent,
        ),
        extendBodyBehindAppBar: true,
        backgroundColor: Colors.transparent,
        body: SafeArea(
          bottom: false,
          child: BackgroundContainer(
            setting: widget.setting,
            enabled: false,
            child: BlocBuilder<GalleryBloc, GalleryState>(
              buildWhen: (previous, current) => current is GalleryItemLoaded,
              builder: (context, state) {
                if (state is GalleryItemLoaded) {
                  if (state.item.id == widget.creativeGallery.id) {
                    return Align(
                      alignment: Alignment.topCenter,
                      child: ConstrainedBox(
                        constraints: const BoxConstraints(
                          maxWidth: CustomSize.smallWindowSize,
                        ),
                        child: SingleChildScrollView(
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Container(
                                margin: const EdgeInsets.only(
                                    top: 5, bottom: 18, left: 22, right: 22),
                                child: MyTextSingle(state.item.content ?? '',
                                    16, Colors.white, FontWeight.w400,
                                    maxLines: 2),
                              ),
                              Container(
                                // decoration: BoxDecoration(
                                //   borderRadius: BorderRadius.circular(11),
                                // ),
                                margin:
                                    const EdgeInsets.symmetric(horizontal: 22),
                                child: WidgetsToImage(
                                  controller: controller,
                                  child: NetworkImagePreviewer(
                                    url: state.item.preview,
                                    notClickable: true,
                                    hidePreviewButton: true,
                                  ),
                                ),
                              ),
                              Row(
                                children: [
                                  const Spacer(),
                                  Container(
                                    height: 32,
                                    width: 90,
                                    margin: const EdgeInsets.only(
                                        right: 24, top: 12),
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(8),
                                      color: Colors.white.withOpacity(0.12),
                                    ),
                                    child: Row(
                                      children: [
                                        GestureDetector(
                                          onTap: () {
                                            var text = state.item.content ?? '';
                                            var replacedString =
                                                text.replaceAll('\\n', '\\\n');
                                            replacedString = replacedString
                                                .replaceAll('\\', '');
                                            FlutterClipboard.copy(
                                                    replacedString)
                                                .then((value) {
                                              showSuccessMessage('已复制到剪贴板');
                                            });
                                          },
                                          child: Container(
                                              color: Colors.transparent,
                                              width: 45,
                                              height: 30,
                                              child: Center(
                                                child:
                                                    imgWidget(17, 17, 'copy'),
                                              )),
                                        ),
                                        Container(
                                          margin: const EdgeInsets.only(
                                              top: 6.5, bottom: 6.5),
                                          color: const Color(0xFF4B4A4D),
                                          width: 1,
                                        ),
                                        GestureDetector(
                                          onTap: () {
                                            int saveTemp = state.item.isLike ?? 0;

                                            state.item.isLike = state.item.isLike == 0 ? 1 : 0;
                                            setState(() {});

                                            // EasyLoading.show(status: '请稍等...');
                                            APIServer()
                                                .photoClickLike(
                                                    state.item.id ?? 0, saveTemp == 0 ? 1 : 0)
                                                .then((value) {
                                              EasyLoading.dismiss();

                                            }).onError((error, stackTrace) {
                                              EasyLoading.dismiss();
                                              showErrorMessage(resolveError(
                                                  context, error!));
                                            });
                                          },
                                          child: Container(
                                              color: Colors.transparent,
                                              width: 40,
                                              height: 30,
                                              child: Center(
                                                  child: imgWidget(
                                                      17,
                                                      17,
                                                      state.item.isLike == 0
                                                          ? 'zan'
                                                          : 'yizan'))),
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                              Container(
                                height: 50,
                                margin: EdgeInsets.only(
                                    left: 22, right: 22, bottom: 36.w, top: 22),
                                width: double.infinity,
                                decoration: const BoxDecoration(
                                  image: DecorationImage(
                                    image:
                                        AssetImage('images/guide_button.png'),
                                    fit: BoxFit.fill,
                                  ),
                                ),
                                child: CupertinoButton(
                                  padding: EdgeInsets.zero,
                                  child: widget.creativeGallery.index == 1
                                      ? MyTextWeight('画同款', 16, Colors.white,
                                          FontWeight.w400)
                                      : Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          children: [
                                            imgWidget(16, 17, 'xiazai'),
                                            const SizedBox(width: 7),
                                            MyTextWeight('下载图片', 16,
                                                Colors.white, FontWeight.w400),
                                          ],
                                        ),
                                  onPressed: () async {
                                    
                                    if (widget.creativeGallery.index == 1) {
                                      if (AppUtil().touristLoginModel?.isVip ==
                                          0) {
                                        // 不是vip需要跳转
                                        context.push('/payment');
                                        return;
                                      }
                                      if (_homeData.needIntegral.value >
                                          _homeData.integral.value) {
                                        // 积分不足
                                        // showErrorMessage('积分不足');
                                        context.push('/integral');
                                        return;
                                      }

                                      // 积分满足
                                      showIntegralTipsDialog(context, () {
                                        var extra = {};
                                        extra['sizeId'] = state.item.sizeId;

                                        if (state.item.styleId != null) {
                                          extra['styleId'] = state.item.styleId;
                                        }
                                        if (isNotBlank(state.item.title ?? '')) {
                                          extra['title'] = state.item.title;
                                        }
                                        if (isNotBlank(
                                            state.item.content ?? '')) {
                                          extra['content'] = state.item.content;
                                        }
                                        Future.delayed(
                                            const Duration(milliseconds: 400))
                                            .then((value) {
                                          context.push('/gallery_start_create',
                                              extra: extra);
                                        });
                                      });
                                    } else {
                                      save();
                                    }
                                  },
                                ),
                              )
                            ],
                          ),
                        ),
                      ),
                    );
                  }
                }
                return Center(
                  child: CircularProgressIndicator(
                      color: customColors.themeBlueColor),
                );
              },
            ),
          ),
        ),
      ),
    );
  }

  /// 显示积分提醒
  showIntegralTipsDialog(
      BuildContext context, Function()? onSubmitCallback) async {
    showAnimationDialog(
      context: context,
      transitionType: TransitionType.inFromTop,
      barrierDismissible: true,
      builder: (diaContext) => StatefulBuilder(builder: (diaContext, state) {
        return Dialog(
          elevation: 0,
          backgroundColor: Colors.transparent,
          child: Container(
            margin: const EdgeInsets.only(bottom: 30),
            width: 320,
            height: 275,
            decoration: BoxDecoration(
              color: const Color(0xFF333544),
              borderRadius: BorderRadius.circular(13),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Padding(
                  padding: const EdgeInsets.only(top: 34),
                  child:
                      MyTextWeight('绘画消耗积分', 18, Colors.white, FontWeight.w500),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 30, bottom: 25),
                  child: MyTextWeight(
                      '每次绘画消耗${_homeData.needIntegral.value}积分，是否确定画画',
                      16,
                      Colors.white,
                      FontWeight.w400),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    MyTextWeight('当前积分：', 16, Colors.white, FontWeight.w400),
                    Padding(
                      padding: const EdgeInsets.only(bottom: 5),
                      child: MyTextWeight('${_homeData.integral.value}', 24,
                          const Color(0xFF18DDEB), FontWeight.w500),
                    ),
                  ],
                ),
                const Spacer(),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Button(
                        title: '取消',
                        color: const Color(0xFF666666),
                        size: const ButtonSize(
                            height: 40, width: 125, fontSize: 16),
                        backgroundColor: const Color(0xFFEEEEEE),
                        borderRadius: 20,
                        onPressed: () {
                          diaContext.pop();
                        }),
                    const SizedBox(width: 12),
                    Button(
                        title: '确定',
                        color: Colors.white,
                        size: const ButtonSize(
                            height: 40, width: 125, fontSize: 16),
                        backgroundColor: const Color(0xFFEEEEEE),
                        borderRadius: 20,
                        gradient: const LinearGradient(
                          colors: [
                            Color(0xFF14E0EB),
                            Color(0xFF5988FC),
                          ],
                          begin: Alignment.centerLeft,
                          end: Alignment.centerRight,
                        ),
                        onPressed: () {
                          if (onSubmitCallback != null) {
                            onSubmitCallback();
                          }
                          diaContext.pop();
                        }),
                  ],
                ),
                const SizedBox(height: 25),
              ],
            ),
          ),
        );
      }),
    );
  }

  void save() async {
    PermissionStatus status = await Permission.photos.status;
    if (!status.isGranted) {
      // 请求权限
      status = await Permission.photos.request();
      if (!status.isGranted) {
        showCupertinoDialog(
            context: context,
            builder: (BuildContext context) {
              return CupertinoAlertDialog(
                title: const Text('提示'),
                content: const Text('您未授权访问相册，无法使用保存相册功能，请在设置中允许访问照片/相册权限后重试'),
                actions: [
                  CupertinoDialogAction(
                    isDefaultAction: true,
                    child: const Text(
                      '取消',
                      style: TextStyle(
                          color: Colors.white, fontWeight: FontWeight.normal),
                    ),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                  CupertinoDialogAction(
                    isDestructiveAction: true,
                    child: const Text('去设置'),
                    onPressed: () {
                      context.pop();
                      launchUrlString('App-Prefs:Privacy&path=PHOTOS');
                    },
                  ),
                ],
                insetAnimationDuration: const Duration(seconds: 2),
              );
            });

        return;
      }
    }


    EasyLoading.show(
        status: '请稍等...',
        maskType: EasyLoadingMaskType.black,
        dismissOnTap: false);
    try {
      final data = await controller.capture();
      EasyLoading.dismiss();
      if (data != null) {
        await ImageGallerySaver.saveImage(data, quality: 100);
        showSuccessMessage('已下载到手机，请通过相册查看');
      }
    } finally {
      EasyLoading.dismiss();
    }
  }
}

class TextItem extends StatefulWidget {
  final String title;
  final String value;

  const TextItem({
    super.key,
    required this.title,
    required this.value,
  });

  @override
  State<TextItem> createState() => _TextItemState();
}

class _TextItemState extends State<TextItem> {
  String valueTranslated = '';

  @override
  Widget build(BuildContext context) {
    final customColors = Theme.of(context).extension<CustomColors>()!;
    return SizedBox(
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            widget.title,
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.bold,
              color: customColors.weakTextColor,
            ),
          ),
          const SizedBox(height: 5),
          GestureDetector(
            onLongPressStart: (details) {
              HapticFeedbackHelper.mediumImpact();

              BotToast.showAttachedWidget(
                target: details.globalPosition,
                duration: const Duration(seconds: 8),
                animationDuration: const Duration(milliseconds: 200),
                animationReverseDuration: const Duration(milliseconds: 200),
                preferDirection: PreferDirection.topCenter,
                ignoreContentClick: false,
                onlyOne: true,
                allowClick: true,
                enableSafeArea: true,
                attachedBuilder: (cancel) => AttachedButtonPanel(
                  buttons: [
                    TextButton.icon(
                      onPressed: () {
                        FlutterClipboard.copy(widget.value).then((value) {
                          showSuccessMessage('已复制到剪贴板');
                        });
                        cancel();
                      },
                      label: const Text(''),
                      icon: const Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(
                            Icons.copy,
                            color: Color.fromARGB(255, 255, 255, 255),
                            size: 14,
                          ),
                          Text(
                            "复制",
                            style: TextStyle(fontSize: 12, color: Colors.white),
                          ),
                        ],
                      ),
                    ),
                    TextButton.icon(
                      onPressed: () {
                        cancel();

                        APIServer().translate(widget.value).then((value) {
                          setState(() {
                            valueTranslated = value.result!;
                          });
                        }).onError((error, stackTrace) {
                          showErrorMessage(resolveError(context, error!));
                        });
                      },
                      label: const Text(''),
                      icon: const Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(
                            Icons.translate,
                            color: Color.fromARGB(255, 255, 255, 255),
                            size: 14,
                          ),
                          Text(
                            '翻译',
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.white,
                            ),
                          )
                        ],
                      ),
                    ),
                  ],
                ),
              );
            },
            child: Text(
              widget.value,
              style: TextStyle(
                fontSize: 12,
                color: customColors.weakTextColor,
              ),
              maxLines: 5,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          if (valueTranslated != '')
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const SizedBox(height: 10),
                Row(children: [
                  Icon(
                    Icons.check_circle,
                    size: 12,
                    color: customColors.linkColor,
                  ),
                  const SizedBox(width: 5),
                  Text(
                    '中文翻译 ↓',
                    style: TextStyle(
                      fontSize: 12,
                      color: customColors.weakTextColor,
                    ),
                  ),
                ]),
                const SizedBox(height: 5),
                GestureDetector(
                  onLongPressStart: (details) {
                    HapticFeedbackHelper.mediumImpact();

                    BotToast.showAttachedWidget(
                      target: details.globalPosition,
                      duration: const Duration(seconds: 8),
                      animationDuration: const Duration(milliseconds: 200),
                      animationReverseDuration:
                          const Duration(milliseconds: 200),
                      preferDirection: PreferDirection.topCenter,
                      ignoreContentClick: false,
                      onlyOne: true,
                      allowClick: true,
                      enableSafeArea: true,
                      attachedBuilder: (cancel) => AttachedButtonPanel(
                        buttons: [
                          TextButton.icon(
                            onPressed: () {
                              FlutterClipboard.copy(valueTranslated)
                                  .then((value) {
                                showSuccessMessage('已复制到剪贴板');
                              });
                              cancel();
                            },
                            label: const Text(''),
                            icon: const Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Icon(
                                  Icons.copy,
                                  color: Color.fromARGB(255, 255, 255, 255),
                                  size: 14,
                                ),
                                Text(
                                  "复制",
                                  style: TextStyle(
                                      fontSize: 12, color: Colors.white),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    );
                  },
                  child: Text(
                    valueTranslated,
                    style: TextStyle(
                      fontSize: 12,
                      color: customColors.weakTextColor,
                    ),
                    maxLines: 5,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            )
        ],
      ),
    );
  }
}
